package cn.jbt.api.admin.util;

import cn.hutool.core.lang.UUID;
import cn.jbt.api.admin.service.ISysConfigService;
import cn.jbt.common.MinioUploadResult;
import cn.jbt.common.util.ApplicationContextUtil;
import cn.jbt.config.MinioOssConfig;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class MinioUtil {

    /**
     * <h2>上传文件</h2>
     */
    public static MinioUploadResult uploadFile(MultipartFile file) {
        ApplicationContext context = ApplicationContextUtil.getContext();
        ISysConfigService iSysConfigService = context.getBean(ISysConfigService.class);

        MinioOssConfig minioOssConfig = (MinioOssConfig) iSysConfigService.getConfig("MinioOss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioOssConfig.getEndpoint())
                .credentials(minioOssConfig.getAccessKey(), minioOssConfig.getSecretKey())
                .build();

        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioOssConfig.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioOssConfig.getBucketName()).build());
            } else {
                log.info("存储桶已经存在");
            }

            // 文件扩展名
            String filenameExt = FilenameUtils.getExtension(file.getOriginalFilename());
            // 文件名称
            String filename = UUID.randomUUID().toString() + '.' + filenameExt;
            // 设置存储对象名称
            String objectName = sdf.format(new Date()) + "/" + filenameExt + "/" + filename;

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioOssConfig.getBucketName())
                    .object(objectName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build();
            minioClient.putObject(putObjectArgs);

            MinioUploadResult minioUploadResult = new MinioUploadResult();
            minioUploadResult.setName(filename);
            minioUploadResult.setUrl(minioOssConfig.getDomain() + "/" + minioOssConfig.getBucketName() + "/" + objectName);
            return minioUploadResult;

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
